package me.chanjar.weixin.mp.api.impl;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.utils.HttpUtils;
import com.platform.common.utils.JedisUtil;
import com.platform.common.utils.SpringContextUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.http.HttpType;
import me.chanjar.weixin.common.util.http.apache.ApacheHttpClientBuilder;
import me.chanjar.weixin.common.util.http.apache.DefaultApacheHttpClientBuilder;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.enums.ComponentConstant;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.util.concurrent.locks.Lock;

/**
 * @author Admin
 */
public class ComponentWxMpServiceHttpClientImpl extends AbstractComponentWxMpServiceImpl<CloseableHttpClient, HttpHost> {
    private static final Logger log = LoggerFactory.getLogger(AbstractComponentWxMpServiceImpl.class);
    private CloseableHttpClient httpClient;
    private HttpHost httpProxy;
    private HttpUtils httpGet = new HttpUtils();

    public ComponentWxMpServiceHttpClientImpl() {
    }

    @Override
    String getComponentAccessToken() {
        WxMpConfigStorage config = this.getWxMpConfigStorage();
        JedisUtil jedisUtil = (JedisUtil) SpringContextUtils.getBean("jedisUtil");
        Long validTime = 1L;
        if (jedisUtil.ttl(ComponentConstant.COMPONENT_ACCESS_TOKEN) > validTime) {
            return jedisUtil.get(ComponentConstant.COMPONENT_ACCESS_TOKEN);
        } else {
            Lock lock = config.getAccessTokenLock();
            String var11;
            lock.lock();
            try {
                StringBuilder stringBuilder = new StringBuilder(ComponentConstant.COMPONENT_TOKEN_URL);
                String time = System.currentTimeMillis() + "";
                String password = new Sha256Hash(ComponentConstant.COMPONENT_AES_KEY, time).toHex();
                stringBuilder.append("?token=").append(password).append("&time=").append(time);

                log.info("第三方接口调用数据获取第三方token：{}", stringBuilder.toString());
                JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(stringBuilder.toString(), "",this.getRequestHttpProxy()));
                log.info("获取第三方token调取接口返回值为：{}", jsonObject);
                if (jsonObject != null || jsonObject.getInteger("code").equals(0)) {
                    jedisUtil.set(ComponentConstant.COMPONENT_ACCESS_TOKEN, jsonObject.getString("token"), jsonObject.getInteger("time"));
                    var11 = jsonObject.getString("token");
                } else {
                    var11 = null;
                }
            } catch (Exception e) {
                log.error("从第三方接口平台中获取第三方token值失败", e);
                var11 = null;
            } finally {
                lock.unlock();
            }

            return var11;
        }
    }

    @Override
    public CloseableHttpClient getRequestHttpClient() {
        return this.httpClient;
    }

    @Override
    public HttpHost getRequestHttpProxy() {
        return this.httpProxy;
    }

    @Override
    public HttpType getRequestType() {
        return HttpType.APACHE_HTTP;
    }

    @Override
    public void initHttp() {
        WxMpConfigStorage configStorage = this.getWxMpConfigStorage();
        ApacheHttpClientBuilder apacheHttpClientBuilder = configStorage.getApacheHttpClientBuilder();
        if (null == apacheHttpClientBuilder) {
            apacheHttpClientBuilder = DefaultApacheHttpClientBuilder.get();
        }

        ((ApacheHttpClientBuilder) apacheHttpClientBuilder).httpProxyHost(configStorage.getHttpProxyHost()).httpProxyPort(configStorage.getHttpProxyPort())
                .httpProxyUsername(configStorage.getHttpProxyUsername()).httpProxyPassword(configStorage.getHttpProxyPassword());
        if (configStorage.getHttpProxyHost() != null && configStorage.getHttpProxyPort() > 0) {
            this.httpProxy = new HttpHost(configStorage.getHttpProxyHost(), configStorage.getHttpProxyPort());
        }

        this.httpClient = ((ApacheHttpClientBuilder) apacheHttpClientBuilder).build();
    }

    @Override
    public String getAccessToken(boolean forceRefresh) throws WxErrorException {
        WxMpConfigStorage config = this.getWxMpConfigStorage();
        if (!config.isAccessTokenExpired() && !forceRefresh) {
            return config.getAccessToken();
        } else {
            Lock lock = config.getAccessTokenLock();
            String var11;
            Jedis jedis = ((ComponentWxMpRedisConfigImpl) config).getJedisPool().getResource();
            lock.lock();
            try {
                StringBuilder stringBuilder = new StringBuilder(ComponentConstant.COMPONENT_URL);
                String time = System.currentTimeMillis() + "";
                String password = new Sha256Hash(ComponentConstant.COMPONENT_AES_KEY, time).toHex();
                stringBuilder.append("?token=").append(password).append("&appId=").append(config.getAppId()).append("&time=").append(time);

                log.info("第三方接口调用数据：{}", stringBuilder.toString());
                JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(stringBuilder.toString(), ""));
                log.info("授权公共号回调后调取接口返回值为：{}", jsonObject);
                if (jsonObject != null || jsonObject.getInteger("code").equals(0)) {
                    config.updateAccessToken(jsonObject.getString("token"), 7200);
                }
                var11 = config.getAccessToken();
            } catch (Exception e) {
                log.error("从第三方接口平台中获取token值失败", e);
                var11 = config.getAccessToken();
            } finally {
                lock.unlock();
                if (jedis != null) {
                    jedis.close();
                }
            }

            return var11;
        }
    }
}
